package com.cskaoyan.service.wxgoods;

import com.cskaoyan.bean.po.ohter.*;
import com.cskaoyan.bean.po.wxorder.MarketComment;
import com.cskaoyan.bean.po.wxorder.MarketCommentExample;
import com.cskaoyan.bean.vo.wxgoods.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.mapper.wxorder.MarketCommentMapper;
import com.cskaoyan.util.beanutils.BeanUtil;
import com.cskaoyan.util.common.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @Author Ajun de BBC
 * @Date 2022/7/19 16:42
 * @Version 1.5
 */

@Service
public class WxGoodsServiceImpl implements WxGoodsService{

    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;


    /**
     *@Description : 显示商品数目
     *@Param :
     *@Return :
     */
    @Override
    public Integer goodsCount() {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andIsOnSaleEqualTo(true);
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        int count = marketGoods.size();
        // for (MarketGoods marketGood : marketGoods) {
        //     count++;
        // }
        return count;
    }

    /**
     *@Description : 显示商品类目
     *@Param :
     *@Return :
     */
    @Override
    public GoodsCategoryVo goodsCategory(Integer id) {
        //显示该类目
        MarketCategory currentCategory = marketCategoryMapper.selectByPrimaryKey(id);
        //显示该类目所属的父类类目
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        marketCategoryExample.createCriteria().andPidEqualTo(currentCategory.getPid());
        List<MarketCategory> brotherCategory = marketCategoryMapper.selectByExample(marketCategoryExample);
        //显示父类目
        MarketCategory parentCategory = marketCategoryMapper.selectByPrimaryKey(currentCategory.getPid());
        GoodsCategoryVo goodsCategoryVo = new GoodsCategoryVo(currentCategory, brotherCategory, parentCategory);

        return goodsCategoryVo;
    }

    /**
     *@Description : 点开类目商品详情
     *@Param :
     *@Return :
     */
    @Override
    public GoodsListVo goodsList(Integer userId,Integer categoryId,Integer brandId,String keyword,Boolean isNew,Boolean isHot,Integer page,Integer limit,String sort,String order) {
        PageHelper.startPage(page,limit);
        //给L2类目下的所有在售商品
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        if(sort != null && order != null){
            marketGoodsExample.setOrderByClause(sort + " " + order);
        }
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        //判断categoryId是否为null，拼接
        if(categoryId != null && categoryId != 0){
            criteria.andCategoryIdEqualTo(categoryId);
        }
        //判断拼接keyword，拼接
        if(keyword != null){
            criteria.andNameLike("%" + keyword + "%");
            //关键字的历史记录
            MarketSearchHistory marketSearchHistory = new MarketSearchHistory(null,userId,keyword,"wx",
                    new Date(System.currentTimeMillis()),new Date(System.currentTimeMillis()),false);
            marketSearchHistoryMapper.insert(marketSearchHistory);
        }

        //判断brandID是否为null，拼接
        if(brandId != null){
            criteria.andBrandIdEqualTo(brandId);
        }
       //判断商品是否在售
        criteria.andIsOnSaleEqualTo(true);
       //判断是否为新品
       if(isNew != null && isNew){
           criteria.andIsNewEqualTo(isNew);
       }
       //判断是否为热销商品
       if(isHot != null && isHot){
           criteria.andIsHotEqualTo(isHot);
       }

        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        //拿到所有商品对应的category即2级类目的id
        List<Integer> categoryL2Id = new ArrayList<>();
        List<GoodsListInfo> goodsListInfos = new ArrayList<>();
        for (MarketGoods marketGood : marketGoods) {
            Integer categoryIdOfGoods = marketGood.getCategoryId();
            categoryL2Id.add(categoryIdOfGoods);
            GoodsListInfo goodsListInfo = new GoodsListInfo();
            BeanUtil.copyBean(marketGood,goodsListInfo);
            goodsListInfos.add(goodsListInfo);
        }

        //拿到的L2类目数组去重
        List<Integer> categoryL2IdWithoutDup = categoryL2Id.stream().distinct().collect(Collectors.toList());
        List<MarketCategory> categoryList = new ArrayList<>();
        //查询得到所有L2类目
        for (Integer categoryL2 : categoryL2IdWithoutDup) {
            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(categoryL2);
            categoryList.add(marketCategory);
        }

        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(marketGoods);
        Long total = marketGoodsPageInfo.getTotal();
        int pages = marketGoodsPageInfo.getPages();
        return new GoodsListVo(total,pages,limit,page,goodsListInfos,categoryList);
    }

    /**
     *@Description : 商品的详细信息
     *@Param :
     *@Return :
     */
    @Override
    public GoodsDetailVo goodsDetailAll(Integer userId,Integer id) {
        //规格表
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        List<MarketGoodsSpecification> specsValueList = new ArrayList<>();
        List<MarketGoodsSpecification> colorValueList = new ArrayList<>();
        for (MarketGoodsSpecification marketGoodsSpecification : marketGoodsSpecifications) {
            if(marketGoodsSpecification.getSpecification().equals("规格")){
                specsValueList.add(marketGoodsSpecification);
            }else {
                colorValueList.add(marketGoodsSpecification);
            }
        }
        //zhong
        List<SpecificationListInfo> specificationList = new ArrayList<>();
        if (specsValueList.size() != 0) {
            specificationList.add(new SpecificationListInfo("规格",specsValueList));
        }
        if (colorValueList.size() != 0) {
            specificationList.add(new SpecificationListInfo("颜色", colorValueList));
        }

        //常见问题表
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        marketIssueExample.createCriteria().andDeletedEqualTo(false);
        marketIssueExample.setOrderByClause("id ASC");
        List<MarketIssue> issueList = marketIssueMapper.selectByExample(marketIssueExample);
        //zhong 7/21 23:29
        /*int size = issueList.size();
        List<MarketIssue> issue = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            issue.add(issueList.remove(random.nextInt(size - i)));
        }*/

        //是否收藏
        //zhong 7/21 23:30
        boolean userHasCollect=false;
        MarketCollectExample collectExample = new MarketCollectExample();
        MarketCollectExample.Criteria collectExampleCriteria = collectExample.createCriteria();
        collectExampleCriteria.andUserIdEqualTo(userId);
        collectExampleCriteria.andValueIdEqualTo(id);
        collectExampleCriteria.andTypeEqualTo((byte) 0);
        collectExampleCriteria.andDeletedEqualTo(false);
        long countCollect = marketCollectMapper.countByExample(collectExample);
        if (countCollect != 0) {
            userHasCollect = true;
        }


        //评论表
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteria = marketCommentExample.createCriteria();
        criteria .andTypeEqualTo((byte)0);
        criteria.andValueIdEqualTo(id);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        //zhong
        GoodsCommentInfo comment = new GoodsCommentInfo();
        comment.setData(marketComments);
        comment.setCount(marketComments.size());

        //zhong 7/21 23:40
        //商品基本信息表
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        GoodsDetailInfoVO info = new GoodsDetailInfoVO();
        try {
            BeanUtils.copyProperties(info,marketGoods);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        String[] gallery = StringUtils.splitJsonArrays(marketGoods.getGallery());
        info.setGallery(gallery);


        //可否分享
        boolean share = true;
        //分享连接
        String shareImage = marketGoods.getShareUrl();

        //商品参数表
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attributeList = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);


        //品牌表
        MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(marketGoods.getBrandId());

        //商品货品表
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        //zhong
        List<GoodsProductInfo> productList = marketGoodsProducts
                .stream()
                .map(product -> {
                    GoodsProductInfo goodsProductInfo = new GoodsProductInfo();
                    try {
                        BeanUtils.copyProperties(goodsProductInfo,product);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    goodsProductInfo
                            .setSpecifications(StringUtils.splitJsonArrays(product.getSpecifications()));
                    return goodsProductInfo;
                })
                .collect(Collectors.toList());

        //zhong 7/22 9:30
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setSpecificationList(specificationList);
        goodsDetailVo.setGroupon("");
        goodsDetailVo.setIssue(issueList);
        goodsDetailVo.setUserHasCollect(userHasCollect);
        goodsDetailVo.setComment(comment);
        goodsDetailVo.setShare(share);
        goodsDetailVo.setShareImage(shareImage);
        goodsDetailVo.setAttribute(attributeList);
        goodsDetailVo.setBrand(marketBrand);
        goodsDetailVo.setProductList(productList);
        goodsDetailVo.setInfo(info);
        return goodsDetailVo;
    }

    @Override
    public GoodsRelatedVo wxGoodsRelated(Integer userId, Integer goodsId) {
        // 根据商品编号查商品类目ID
        MarketGoods marketGoods1 = marketGoodsMapper.selectByPrimaryKey(goodsId);
        Integer categoryId = marketGoods1.getCategoryId();
        // 根据类目Id查相关商品
        MarketGoodsExample example2 = new MarketGoodsExample();
        example2.createCriteria()
                .andCategoryIdEqualTo(categoryId)
                .andIsOnSaleEqualTo(true)
                .andDeletedEqualTo(false);
        List<MarketGoods> marketGoods2 = marketGoodsMapper.selectByExample(example2);

        // 将相关商品的加入列表
        List<GoodsListInfo> list = new ArrayList<>();
        int count = 0;
        if (count < 6) {
            for (MarketGoods marketGoods : marketGoods2) {
                GoodsListInfo info = new GoodsListInfo();
                BeanUtil.copyBean(marketGoods, info);
                list.add(info);
                count++;
                if (count >= 6) break;
            }
        }

        // 如果相关商品数量不够，加入其它商品
        if (count < 6) {
            MarketGoodsExample example3 = new MarketGoodsExample();
            example3.createCriteria()
                    .andIsOnSaleEqualTo(true)
                    .andDeletedEqualTo(false);
            List<MarketGoods> marketGoods3 = marketGoodsMapper.selectByExample(example3);
            for (MarketGoods marketGoods : marketGoods3) {
                GoodsListInfo info = new GoodsListInfo();
                BeanUtil.copyBean(marketGoods, info);
                list.add(info);
                count++;
                if (count++ >= 6) break;
            }
        }
        GoodsRelatedVo goodsRelatedVo = new GoodsRelatedVo();
        goodsRelatedVo.setList(list);
        goodsRelatedVo.setTotal((long) list.size());
        goodsRelatedVo.setPages(1);
        goodsRelatedVo.setLimit(6);
        goodsRelatedVo.setPage(1);

        return goodsRelatedVo;
    }
}
